package cn.com.lyb.asyncTask.manage;



import cn.com.lyb.asyncTask.construnctor.AsyncTaskConstructor;
import cn.com.lyb.asyncTask.entity.TaskInfo;
import cn.com.lyb.asyncTask.entity.TaskStatusEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 异步任务aop监控
 */
@Component
@Aspect
public class AsyncTaskAop {

    private static Logger LOG = LoggerFactory.getLogger(AsyncTaskAop.class);

    @Autowired
    AsyncTaskManager manager;

    @Around("execution(* cn.com.lyb.asyncTask.manage.AsyncTaskExecutor.executor(..))")
    public void taskHandle(ProceedingJoinPoint pjp) {
        // 获取构造器
        AsyncTaskConstructor taskConstructor = (AsyncTaskConstructor) pjp.getArgs()[0];
        //获取taskId
        String taskId = pjp.getArgs()[1].toString();
        //获取任务信息
        TaskInfo taskInfo = manager.getTaskInfo(taskId);
        LOG.info("AsyncTaskMonitor is monitoring async task:{}", taskId);
        taskInfo.setStatus(TaskStatusEnum.RUNNING);
        manager.setTaskInfo(taskInfo);
        TaskStatusEnum status;
        Throwable exception = null;
        try {
            pjp.proceed();
            status = TaskStatusEnum.SUCCESS;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            LOG.error("AsyncTaskMonitor:async task {} is failed.Error info:{}", taskId, throwable.getMessage());
            status = TaskStatusEnum.FAILED;
            exception = throwable;
        }
        taskInfo.setEndTime(new Date());
        taskInfo.setStatus(status);
        taskInfo.setTotalTime();
        manager.setTaskInfo(taskInfo);

        if (status == TaskStatusEnum.SUCCESS) {
            taskConstructor.callBackAfterSuccess();
        } else {
            taskConstructor.callBackAfterFail(exception);
        }
    }
}